package com.idriver.util;

import org.apache.commons.dbcp.BasicDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class DBCPUtil {

    public static final String DRIVER_NAME = "com.mysql.jdbc.Driver";

    public static final String URL = "jdbc:mysql://localhost:3306/db_web?characterEncoding=UTF-8";

    public static final String USER = "root";

    public static final String PASSWORD = "root";

    public static BasicDataSource datasource = new BasicDataSource();

    static {
        datasource.setDriverClassName(DRIVER_NAME);
        datasource.setUrl(URL);
        datasource.setUsername(USER);
        datasource.setPassword(PASSWORD);
    }

    public static DataSource getDataSource() {
        return datasource;
    }

    public static Connection getConnection() throws SQLException {

        return datasource.getConnection();
    }

    public static void close(Connection connection, Statement statement) {

        if (null != connection && null != statement) {
            try {
                statement.close();
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    public static void close(Connection connection, Statement statement, ResultSet resultSet) {

        if (null != connection && null != statement && null != resultSet) {
            try {
                resultSet.close();
                statement.close();
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
